<?php

class Sistema_RepositorioController extends App_Controller_Action
{
    private $_table     = 'REPOSITORIO';
    private $_pk        = 'REP_ID';
    private $_order_col = 'REP_NOM';
    private $_order     = 'ASC';
    private $_sta_col   = 'REP_STA';
    private $obj        = '';
    private $form       = '';
    public  $dir        = 'public/upload/repositorio/';
    public  $_file_col  = 'REP_FILE';
    
    private $_PER_ID;
    private $_USU_ID;
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Sistema_Form_Repositorio();
        
        $auth = Zend_Auth::getInstance();
        $s_user = $auth->getStorage();
        $this->_PER_ID = $s_user->read()->PER_ID;
        $this->_USU_ID = $s_user->read()->USU_ID;
    }

    public function indexAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_list.js');
        
        $where = 'REP_STA = "1"';
        
        $dsfiltro= $this->_getParam('dsfiltro', '');
        if(strlen($dsfiltro) > 1) $where .= ' AND REP_NOM like "'.$dsfiltro.'%"';
        $this->view->dsfiltro = $dsfiltro;

        $TIP_ID = $this->_getParam('TIP_ID', 0);
        if($TIP_ID > 0) $where .= ' AND TIP_ID = '.$TIP_ID;
        
        
        if($this->_PER_ID <> 1){
            $where .= ' AND r.USU_ID = '.$this->_USU_ID;
        }
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' r, TIPOMATERIAL m WHERE r.TIP_ID = m.TIP_ID AND '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order.', REP_PRTNUM ASC ';
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
    }
    
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_geral.js');
        
        Zend_Loader::loadClass('imagem','library');
        
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if ($this->form->isValid($formData)) {
                    $id = (int) $this->form->getValue('REP_ID');
                    if($id > 0 && is_uploaded_file($_FILES['REP_FILE'])){
                        imagem::delete($this->getNomeArquivo($id),$this->dir);
                    }
                    $returnImg = imagem::upload('REP_FILE',$this->dir,$id);

                    $datahora = date('Y-m-d H:i:00'); // 0000-00-00 00:00:00
                    $data = $this->form->getValues();
                    $data['REP_EXT'] = $returnImg['ext'];
                    unset($data['REP_FILE']);
                    unset($data['img']);
                    
                    if($data['REP_PRTQTD'] <= 0) $data['REP_PRTQTD'] = 1;
                    if($data['REP_PRTNUM'] <= 0) $data['REP_PRTNUM'] = 1;
                    
                    
                    if ($id == 0){
                        $data['REP_DATHOR'] = $datahora;
                        $data['USU_ID'] = $this->_USU_ID;
                        
                        $this->db->insert($this->_table,$data);

                        if(strlen($returnImg['filenew']) > 0){
                            $id = $this->db->lastInsertId();                  
                            $_id = imagem::formatNomeArquivo($id,$datahora);

                            imagem::rename($_id,$this->dir,$returnImg['filenew']);
                            
                            chmod($this->dir.$_id.'.'.end(explode('.', $returnImg['filenew'])), 0644);
                        }
                    }
                    else{
                        $this->db->update($this->_table,$data, 'REP_ID = ' . $id);

                        if(strlen($returnImg['filenew']) > 0){
                            $_id = $this->getNomeArquivo($id);
                            
                            // deleta arquivo para update
                            imagem::delete($_id,$this->dir);
                            
                            imagem::rename($_id,$this->dir,$returnImg['filenew']);
                            
                            chmod($this->dir.$_id.'.'.end(explode('.', $returnImg['filenew'])), 0644);
                        }
                    }
                   $this->_helper->redirector('index');
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
            }  
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id;
                $data = $this->db->fetchRow($query);
                $this->form->populate($data);
            }
        }
    }

    public function deleteAction() {
        Zend_Loader::loadClass('imagem','library');
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE; 
        
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {
            imagem::delete($this->getNomeArquivo($id),$this->dir);
            
            $data = array('REP_STA'=>0);
            
            $ok = (bool) $this->db->update($this->_table,$data,'REP_ID = '.(int)$id);

        }
        
        echo json_encode(array('ok' => $ok));
    }
    
    public function getNomeArquivo($id) {
        Zend_Loader::loadClass('imagem','library');
        
        $query = 'SELECT SQL_CACHE REP_ID,REP_DATHOR FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id;
        $res = $this->db->fetchRow($query);
        
        return  imagem::formatNomeArquivo($res['REP_ID'],$res['REP_DATHOR']);
    }
    
    public function findAction(){
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
       
        $q = strtolower($this->_getParam('term'));
        
        $index = array();
        $result = array();
        $where = 'REP_STA = 1 and REP_NOM like "'.$q.'%"';
        
        if($this->_getParam('tipmat') > 0)
            $where .= ' and TIP_ID = '.$this->_getParam('tipmat');
        
        $query = 'SELECT SQL_CACHE REP_ID, REP_NOM FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order.', REP_PRTNUM ASC ';
        $rows = $this->db->fetchAll($query);
        foreach ($rows as $res) {
            if(strpos(strtolower($res['REP_NOM']), $q) !== false && array_search($res['REP_NOM'], $index) === false) {
                array_push($result, array("id"=>$res['REP_ID'],"label"=>$res['REP_NOM'],"value" => $res['REP_NOM']));
                $index[] = $res['REP_NOM']; 
            }
            if(count($result) > 20) break;
        }

        echo json_encode($result);
    }
    
    public function arquivoAction(){
        $this->_helper->layout->disableLayout(); 
        
        $search = $this->_getParam('inp-search', '');
        $this->view->search = $search;
        $where = 'REP_STA = 1 and REP_ID > 0';
        if(strlen($search) > 1){
            $where = 'REP_NOM like "%'.$search.'%"';
        }
       
        $TIP_ID = $this->_getParam('TIP_ID', 0);
        if($TIP_ID > 0) $where .= ' and TIP_ID = '.$TIP_ID;
        
        if($this->_getParam('tipmat') > 0){
            $where .= ' and TIP_ID = '.$this->_getParam('tipmat');
            $this->view->headScript()->appendScript('var tipmat = '.$this->_getParam('tipmat').' ;');
        }
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' r, TIPOMATERIAL m WHERE r.TIP_ID = m.TIP_ID AND '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order.', REP_PRTNUM ASC ';
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
    }

}

